package baoycode.utils;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class SerializeUtils {

	public static Object deserializeDecoder(String filePath) {
		Object obj = null;
		try {
			File fin = new File(filePath);
			if (fin.exists()) {
				FileInputStream fis = new FileInputStream(fin);
				XMLDecoder decoder = new XMLDecoder(fis);
				obj = decoder.readObject();
				fis.close();
				decoder.close();
			}
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return obj;

	}

	public static void serializeEncoder(Object data, String fileName) {
		try {
			if (fileName == null || fileName.length() == 0)
				return;
			File file = new File(fileName);
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			file.createNewFile();
			FileOutputStream fos = new FileOutputStream(file);
			XMLEncoder encoder = new XMLEncoder(fos);
			encoder.writeObject(data);
			encoder.flush();
			encoder.close();
			fos.close();
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		} catch (Exception e1) {
			e1.printStackTrace();
		}
	}
}
